/**
 * 
 */
package org.tio.im.server.http.api;

import java.util.HashMap;
import java.util.Map;

import org.tio.core.ChannelContext;
import org.tio.im.common.Const;
import org.tio.im.common.ImPacket;
import org.tio.im.common.http.HttpConfig;
import org.tio.im.common.http.HttpRequest;
import org.tio.im.common.http.HttpResponse;
import org.tio.im.common.packets.Command;
import org.tio.im.common.tcp.TcpPacket;
import org.tio.im.server.command.handler.ChatReqHandler;
import org.tio.im.server.http.annotation.RequestPath;
import org.tio.im.server.util.HttpResps;
import org.tio.utils.json.Json;
/**
 * 版本: [1.0]
 * 功能说明: 
 * 作者: WChao 创建时间: 2017年8月8日 上午9:08:48
 */
@RequestPath(value = "/api")
public class HttpApiController {
	
	@RequestPath(value = "/message/send")
	public HttpResponse chat(HttpRequest request, HttpConfig httpConfig, ChannelContext channelContext)throws Exception {
		HttpResponse response = new HttpResponse(request,httpConfig);
		ImPacket chatPacket = new ChatReqHandler().handler(request, channelContext);
		if(chatPacket != null){
			response = (HttpResponse)chatPacket;
		}
		return response;
	}
	/**
	 * 发送消息
	 * @param user->id 往哪个用户发送,sign->发送的消息
	 * @param request
	 * @param channelContext
	 * @return
	 * @throws Exception
	 */
	@RequestPath(value = "/chat/send")
	public HttpResponse sendChat(HttpRequest request, ChannelContext channelContext) throws Exception {
		TcpPacket tcpPacket = new TcpPacket(Command.COMMAND_CHAT_REQ,request.getBody());		
		HttpResponse response = null;
		ImPacket chatPacket = new ChatReqHandler().handler(tcpPacket, channelContext);
		if(chatPacket != null){
			response = (HttpResponse)chatPacket;
			String json = new String(response.getBody(), Const.CHARSET);
			response = HttpResps.json(request, json);
		}else {
			Map<String,Object> map = new HashMap<>(3);
			map.put("code", 102);
			map.put("msg", "发送失败");
			String json = Json.toFormatedJson(map);
			response = HttpResps.json(request, json);
		}
		return response;
	}
}
